﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace MusicCatalogue
{
    class HardDriveTraverser
    {
        public HardDriveTraverser()
        {
            
        }

        public void GenerateXml(DirectoryInfo direcotory)
        {
            string fileName;
            Encoding encoding;
            SetFileNameAndEncoding(out fileName, out encoding);
            using (XmlTextWriter writer = new XmlTextWriter(fileName, encoding))
            {
                FormatDocument(writer);
                writer.WriteStartDocument();
                writer.WriteStartElement("directories");
                ProcesDirectoryInfo(writer,direcotory);
                writer.WriteEndDocument();
            }
        }
  
        private void ProcesDirectoryInfo(XmlTextWriter writer, DirectoryInfo directory)
        {
            writer.WriteStartElement("directory");
            writer.WriteAttributeString("name",directory.Name);
            FileInfo[] fileArray = directory.GetFiles();
            foreach (var file in fileArray)
            {
                writer.WriteElementString("file",file.Name);
            }
            DirectoryInfo[] directoryArray = directory.GetDirectories();
            foreach (var direc in directoryArray)
            {
                ProcesDirectoryInfo(writer,direc);
            }
            writer.WriteEndElement();
        }
  
        private void FormatDocument(XmlTextWriter writer)
        {
            writer.Formatting = Formatting.Indented;
            writer.IndentChar = '\t';
            writer.Indentation = 1;
        }
  
        private void SetFileNameAndEncoding(out string fileName, out Encoding encoding)
        {
            fileName = "../../directories.xml";
            encoding = Encoding.GetEncoding("windows-1251");
        }
    }
}
